<template>
	<view class="box">
		<image class="bg" src="/static/games/whackMole/bg.jpg">
		</image>
		<view class="result flex_col flex_col_2">
			<view class="align_l">时间：{{duration}}</view>
			<view class="align_r">得分：{{countResult}}</view>
		</view>
		<view class="flex_col flex_col_3 flex_wrap">
			<view class="item" v-for="(item,index) in list" :key="index" @tap="whack(index)">
				<image src="/static/games/whackMole/hole.png" mode="aspectFit" class="hole"></image>
				<image src="/static/games/whackMole/mouse.png" mode="aspectFit" class="mouse" v-show="item == 1"></image>
				<image src="/static/games/whackMole/boom.png" mode="aspectFit" class="boom" v-show="item == 2"></image>
			</view>
		</view>
		<view class="tips padding-lg">
			<view class="cu-tips text-center text-white">在{{ duration }}秒内得分超过{{ fraction }}即可获取奖励哦</view>
		</view>
		<view class="flex padding-lg justify-center" style="display: none;">
			<button class="cu-btn bg-white">再来一次</button>
			<button class="cu-btn bg-white margin-left">分享</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				list:[0,0,0,0,0,0,0,0,0],	//数值说明 0:无状态,1:老鼠显示,2:砸中状态
				result:0,
				duration:60,
				fraction:300,
				flag: !0,
			}
		},
		mounted() {
			this.loadData()
		},
		computed:{
			// 计算结果，使用计算函数，可方便管理得分基数
			countResult(){
				return this.result * 10;
			}
		},
		onUnload(){
			// 页面关闭移除计时器，否则app平台有BUG
			clearTimeout(this.aTime);
			clearInterval(this.bTime);
			clearInterval(this.cTime);
		},

		methods: {
			loadData: function() {
				let that = this;
				let timestamp = this.helper.now();
				let sign = this.helper.setSign(['type='+'whackmole_fraction','timestamp='+timestamp]);
				this.helper.req({
					api:"getRewardSet",
					timestamp:timestamp,
					data:{type:'whackmole_fraction'},
					header:{sign:sign},
					method:'GET',
				}).then(res=>{
					this.fraction = parseInt(res.data.data.reward);
					let msg = "在"+this.duration+"秒内得分超过"+this.fraction+"即可获取奖励哦，是否开始？";
					uni.showModal({
						title: "提示",
						content: msg,
						showCancel: !0,
						confirmText: "开始",
						success:function(res){
							if(res.confirm){
								clearTimeout(that.aTime);
								clearInterval(that.bTime);
								clearInterval(that.cTime);
								
								that.downTime();
								that.showMouse();
							}else{
								uni.navigateBack();
							}
						}
					})
				})
			},
			// 锤打
			whack(i){
				// 非老鼠显示状态则结束事件
				if(this.list[i] != 1){
					return;
				}
				
				if(!this.flag){
					uni.showToast({
						title:'时间已结束',
						icon:'none'
					})
					return;
				}
								
				this.$set(this.list,i,2);
				this.result ++ ;
				
				// 创建匿名函数，使当前序号拥有独立作用域（减少BUG产生）
				((j)=>{
					this.aTime = setTimeout(()=>{
						this.$set(this.list,j,0);
					},800);
				})(i)
			},
			// 显示老鼠
			showMouse(){
				// 获取有效的洞穴,避免重复渲染
				let effective = ()=>{
					let arr = [];
					this.list.forEach((v,i)=>{
						// 将无状态的洞穴添加到可用数组中
						if(v == 0){
							arr.push(i);
						}
					})
					
					return arr;
				}
				
				this.bTime = setInterval(()=>{
					if(!this.flag){
						return;
					}
					let effectiveArr = effective();
					
					// 当可用洞穴数小于3个时不再显示更多的老鼠
					if(effectiveArr.length<3){
						return;
					}
					
					// 随机获得一个可用的洞穴序号
					let r = Math.floor(Math.random()*effectiveArr.length);
					
					// 将可用的洞穴显示老鼠
					this.$set(this.list,effectiveArr[r],1);
				},500);
			},
			// 重新开始
			restart(){
				this.list=[0,0,0,0,0,0,0,0,0];
				this.result=0;
				this.duration = 30;
				this.downTime();
			},
			// 倒计时
			downTime(){
				clearTimeout(this.aTime);
				clearInterval(this.bTime);
				clearInterval(this.cTime);
				this.cTime = setInterval(()=>{
					if(this.duration>0){
						this.duration -- ;
					}else{
						if(this.flag){
							this.flag = false;
							
							if(this.countResult >= this.fraction){
								var info = uni.getStorageSync("userinfo");
								let timestamp = this.helper.now();
								let sign = this.helper.setSign(['fraction='+this.countResult,'token='+info.token,'timestamp='+timestamp]);
								this.helper.req({
									api:"whackmoleVerify",
									timestamp:timestamp,
									data:{fraction:this.countResult,token:info.token},
									header:{sign:sign},
									method:'POST',
								}).then(res=>{
									uni.showModal({
										title:"提示",
										content:res.data.message,
										showCancel:false,
										confirmText:"确定",
										success:(e)=>{
											if(e.confirm){
												uni.redirectTo({
													url: '/pages/tasks/index',
												});	
											}
										}
									})
								})
							}else{
								showPop();
							}
						}
					}
				},1000);
				
				let showPop = ()=>{
					uni.showModal({
						title:"游戏结束",
						content:`得分：${this.countResult}`,
						cancelText:"不玩了",
						confirmText:"重新挑战",
						success:(e)=>{
							if(e.confirm){
								this.restart();
							}
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	body {
	    background-color: #f3f3f3;
	    background-color: initial
	}
	page {
		background-color: initial;
		font-size: 14px;
		box-sizing: border-box;
		color: #333;
		letter-spacing: 0;
		word-wrap: break-word
	}
.uni-page-head-transparent .uni-page-head-btn {
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    -webkit-box-align: center;
    -webkit-align-items: center;
    align-items: center;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.5);
}
</style>